// index.js
const app = getApp()
Page({
  data: {
    
  },
  onLoad(){
    wx.getSetting({
      success(res){
        console.log(res)
      }
    })
  },
  login(){
    var that = this;
    wx.getSetting({
    success: function(res){
      console.log("yes")
    }
    })
    wx.cloud.callFunction({
      name:"login",
      success:res=>{
        console.log("成功！")
        that.setData({
          openid: res.result.openid,
          
        })
        console.log(that.data.openid)
      }
    })
    
    wx.getUserProfile({
      desc: '用于收集信息',
      success(res){
        console.log(res.userInfo)
        var user = res.userInfo
        app.globalData.userInfo = user

        that.setData({
          userInfo: user
        })
        wx.cloud.database().collection('login_users').where({
          _openid: app.globalData.openid
        }).get({
          success(res){
            console.log(res)
            if(res.data.length == 0){
              wx.cloud.database().collection('login_users').add({
          
                data:{
                  
                  avatarUrl : user.avatarUrl,
                  nickName : user.nickName
                },
                success(res){
                  console.log(res)
                  console.log(that.data.openid)
                  wx.showToast({
                    title: '登录成功！',
                  })
                }
                
              })
            }else{
              that.setData({
                userInfo:res.data[0]
              })
            }
          }
        })
        
      }
    })
  },
  loginOut(){
    app.globalData.userInfo = null,
    this.setData({
      userInfo:null
    })
    wx.showToast({
      title: '退出登录！',
    })
  },
  change(){
    wx.navigateTo({
      url: '/pages/ooo/ooo'
    })
  }
})
